package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.UserMoneyDao;
import com.leoman.entity.UserMoney;
import com.leoman.pay.excute.PayRequest;
import com.leoman.service.UserMoneyService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * UserMoneyServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:02.
 */
@Service
public class UserMoneyServiceImpl implements UserMoneyService {

    @Autowired
    private UserMoneyDao userMoneyDao;

    @Override
    public List<UserMoney> findAll() {
        return userMoneyDao.findAll();
    }

    @Override
    public Page<UserMoney> find(int pageNum, int pageSize) {
        return userMoneyDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<UserMoney> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public UserMoney getById(int id) {
        return userMoneyDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        userMoneyDao.delete(id);
    }

    @Override
    public UserMoney create(UserMoney userMoney) {
        return userMoneyDao.save(userMoney);
    }

    @Override
    public UserMoney update(UserMoney userMoney) {
        return userMoneyDao.save(userMoney);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<UserMoney> pageByParams(final Integer type,
                                        final String nickName,
                                        final String account,
                                        final Integer userType,
                                        final Integer accountType,
                                        final String startTime,
                                        final String endTime,
                                        Integer pageNum,
                                        Integer pageSize) {
        return userMoneyDao.findAll(new Specification<UserMoney>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<UserMoney> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (null != type) {
                    predicateList.add(cb.equal(root.get("type").as(Integer.class), type));
                }

                if (StringUtils.isNotBlank(nickName)) {
                    predicateList.add(cb.like(root.get("user").get("nickName").as(String.class), "%" + nickName + "%"));
                }

                if (StringUtils.isNotBlank(account)) {
                    predicateList.add(cb.like(root.get("account").as(String.class), "%" + account + "%"));
                }

                if (null != userType) {
                    predicateList.add(cb.equal(root.get("user").get("type").as(Integer.class), userType));
                }

                if (null != accountType) {
                    predicateList.add(cb.equal(root.get("platform").as(Integer.class), accountType));
                }

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        System.out.println("_");
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        System.out.println("_");
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Integer confirmMoney(Integer userMoneyId) {
        try {
            UserMoney userMoney = userMoneyDao.findOne(userMoneyId);
            userMoney.setRequestStatus(Constant.GIVE_MONEY_STATUS_YES);
            userMoneyDao.save(userMoney);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchConfirm(String ids) {
        try {
            Integer[] userMoneyIds = JsonUtil.json2Obj(ids, Integer[].class);
            UserMoney userMoney;

            for (Integer userMoneyId : userMoneyIds) {
                userMoney = userMoneyDao.findOne(userMoneyId);

                if (userMoney.getRequestStatus().equals(Constant.GIVE_MONEY_STATUS_YES)) {
                    continue;
                }

                userMoney.setRequestStatus(Constant.GIVE_MONEY_STATUS_YES);
                userMoneyDao.save(userMoney);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public void changeMoneyStatus(Integer id) {
        UserMoney userMoney = userMoneyDao.findOne(id);

        if (null != userMoney) {
            userMoney.setRequestStatus(Constant.USER_STATUS_YES);
            userMoneyDao.save(userMoney);
        }
    }

    @Override
    public Map<String, Object> getPayInfo(HttpServletRequest request, HttpServletResponse response, String orderNum, String money) {
        // 微信
        request.setAttribute("fee", money);
        request.setAttribute("sn", orderNum);
        request.setAttribute("prepayid", "");//预支付款ID

        return PayRequest.pay(request, response);
    }
}